package xyz.jcat.biz.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.jcat.biz.admin.AdminRedisKey;
import xyz.jcat.biz.admin.domain.dao.IRolePermissionDao;
import xyz.jcat.biz.admin.domain.dto.RolePermissionBindDto;
import xyz.jcat.biz.admin.domain.po.RolePermissionPo;
import xyz.jcat.biz.admin.domain.po.RolePo;
import xyz.jcat.biz.admin.service.IRolePermissionService;
import xyz.jcat.biz.admin.service.IRoleService;
import xyz.jcat.common.util.CollectionUtils;
import xyz.jcat.common.web.RespCodeMsg;
import xyz.jcat.mybatis.ServiceImpl;
import xyz.jcat.redis.RedisUtils;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 * @author yueyue
 * auto on 2022-04-28 13:41:47
 */
@Service
public class RolePermissionService extends ServiceImpl<IRolePermissionDao, RolePermissionPo> implements IRolePermissionService {

    @Autowired
    private IRoleService roleService;

    @Override
    public List<Long> getRoleIdsByPermission(String permission) {
        Optional<List<Long>> roleIdsOpt = RedisUtils.hashGetList(AdminRedisKey.PERMISSION_ROLES, permission, Long.class);
        if(roleIdsOpt.isPresent()){
            return roleIdsOpt.get();
        }
        List<Long> roleIdsByPermission = dao.getRoleIdsByPermission(permission);
        RedisUtils.hashPut(AdminRedisKey.PERMISSION_ROLES, permission, roleIdsByPermission);
        return roleIdsByPermission;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindRolePermission(RolePermissionBindDto rolePermissionBindDto) {
        Long roleId = rolePermissionBindDto.getRoleId();
        RolePo role = roleService.getById(roleId);
        RespCodeMsg.DATA_NOT_FOUND.isNull(role);
        deleteByRoleId(roleId);
        Set<Long> permissionIds = rolePermissionBindDto.getPermissionIds();
        if(CollectionUtils.isEmpty(permissionIds))
            return;
        List<RolePermissionPo> list = permissionIds.stream().map(permissionId -> {
            RolePermissionPo rolePermission = new RolePermissionPo();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            return rolePermission;
        }).collect(Collectors.toList());
        insertBatch(list);
        //删除permission缓存
        RedisUtils.del(AdminRedisKey.PERMISSION_ROLES);
    }

    private void deleteByRoleId(Long roleId) {
        LambdaQueryWrapper<RolePermissionPo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RolePermissionPo::getRoleId, roleId);
        dao.delete(lambdaQueryWrapper);
    }
}
